package com.crowntit.domain.activity.service.trail.node;

import com.alibaba.fastjson.JSON;
import com.crowntit.domain.activity.model.entity.MarketProductEntity;
import com.crowntit.domain.activity.model.entity.TrialBalanceEntity;
import com.crowntit.domain.activity.model.valobj.GroupBuyActivityDiscountVO;
import com.crowntit.domain.activity.model.valobj.SkuVO;
import com.crowntit.domain.activity.service.discount.IDiscountCalculateService;
import com.crowntit.domain.activity.service.trail.AbstractGroupBuyMarketSupport;
import com.crowntit.domain.activity.service.trail.factory.DefaultActivityStrategyFactory;
import com.crowntit.domain.activity.service.trail.thread.QueryGroupBuyActivityDiscountVOThreadTask;
import com.crowntit.domain.activity.service.trail.thread.QuerySkuVOThreadTask;
import com.crowntit.types.design.framework.tree.StrategyHandler;
import com.crowntit.types.enums.ResponseCode;
import com.crowntit.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.*;

@Slf4j
@Service
public class MarketNode extends AbstractGroupBuyMarketSupport<MarketProductEntity, DefaultActivityStrategyFactory.DynamicContext, TrialBalanceEntity> {

    @Resource
    private TagNode tagNode;
    @Resource
    private ErrorNode errorNode;
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;
    @Resource
    private Map<String, IDiscountCalculateService> discountCalculateServiceMap;

    @Override
    protected void multiThread(MarketProductEntity requestParameter, DefaultActivityStrategyFactory.DynamicContext dynamicContext) throws ExecutionException, InterruptedException, TimeoutException {
        QueryGroupBuyActivityDiscountVOThreadTask queryGroupBuyActivityDiscountVOThreadTask = new QueryGroupBuyActivityDiscountVOThreadTask(requestParameter.getActivityId(), requestParameter.getChannel(), requestParameter.getSource(), activityRepository);
        FutureTask<GroupBuyActivityDiscountVO> queryGroupBuyActivityDiscountVOFutureTask = new FutureTask<>(queryGroupBuyActivityDiscountVOThreadTask);
        threadPoolExecutor.execute(queryGroupBuyActivityDiscountVOFutureTask);

        QuerySkuVOThreadTask querySkuVOThreadTask = new QuerySkuVOThreadTask(requestParameter.getGoodsId(), requestParameter.getSource(), requestParameter.getChannel(), activityRepository);
        FutureTask<SkuVO> querySkuVOFutureTask = new FutureTask<>(querySkuVOThreadTask);
        threadPoolExecutor.execute(querySkuVOFutureTask);

        GroupBuyActivityDiscountVO groupBuyActivityDiscountVO = queryGroupBuyActivityDiscountVOFutureTask.get(timeout, TimeUnit.MINUTES);
        SkuVO skuVO = querySkuVOFutureTask.get(timeout, TimeUnit.MINUTES);
        dynamicContext.setSkuVO(skuVO);
        dynamicContext.setGroupBuyActivityDiscountVO(groupBuyActivityDiscountVO);

        log.info("拼团商品查询试算服务-MarketNode userId:{} 异步线程加载数据「GroupBuyActivityDiscountVO、SkuVO」完成", requestParameter.getUserId());
    }

    @Override
    protected TrialBalanceEntity doApply(MarketProductEntity requestParameter, DefaultActivityStrategyFactory.DynamicContext dynamicContext) throws Exception {
        log.info("拼团商品查询试算服务-MarketNode userId:{} requestParameter:{}", requestParameter.getUserId(), JSON.toJSONString(requestParameter));

        SkuVO skuVO = dynamicContext.getSkuVO();
        if (skuVO == null){
            log.info("目标sc无商品");
            return router(requestParameter, dynamicContext);
        }

        GroupBuyActivityDiscountVO groupBuyActivityDiscountVO = dynamicContext.getGroupBuyActivityDiscountVO();
        if (groupBuyActivityDiscountVO == null){
            log.info("无目标活动配置");
            return router(requestParameter, dynamicContext);
        }

        GroupBuyActivityDiscountVO.GroupBuyDiscount groupBuyDiscount = groupBuyActivityDiscountVO.getGroupBuyDiscount();
        if (groupBuyDiscount == null){
            log.info("目标活动无折扣配置");
            return router(requestParameter, dynamicContext);
        }

        String userId = requestParameter.getUserId();
        IDiscountCalculateService discountCalculateService = discountCalculateServiceMap.get(groupBuyDiscount.getMarketPlan());
        if (null == discountCalculateService) {
            log.info("不存在{}类型的折扣计算服务，支持类型为:{}", groupBuyDiscount.getMarketPlan(), JSON.toJSONString(discountCalculateServiceMap.keySet()));
            throw new AppException(ResponseCode.E0001.getCode(), ResponseCode.E0001.getInfo());
        }

        BigDecimal originalPrice = skuVO.getOriginalPrice();
        BigDecimal payPrice = discountCalculateService.calculate(userId, originalPrice, groupBuyDiscount);
        BigDecimal deductionPrice = originalPrice.subtract(payPrice);

        dynamicContext.setDeductionPrice(deductionPrice);
        dynamicContext.setPayPrice(payPrice);

        return router(requestParameter, dynamicContext);
    }

    @Override
    public StrategyHandler<MarketProductEntity, DefaultActivityStrategyFactory.DynamicContext, TrialBalanceEntity> get(MarketProductEntity requestParameter, DefaultActivityStrategyFactory.DynamicContext dynamicContext) throws Exception {
        if (dynamicContext.getSkuVO() == null || dynamicContext.getGroupBuyActivityDiscountVO() == null || dynamicContext.getGroupBuyActivityDiscountVO().getGroupBuyDiscount() == null || dynamicContext.getDeductionPrice() == null){
            return errorNode;
        }
        return tagNode;
    }
}